package com.example.onlineeducation.ui.offline

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.baidu.location.BDLocation
import com.example.onlineeducation.App
import com.example.onlineeducation.base.BaseActivity
import com.example.onlineeducation.data.constant.OfflineStudyLiveState
import com.example.onlineeducation.databinding.OfflineStudyDetailAcBinding
import com.example.onlineeducation.utils.BaiduLocationUtil
import com.example.onlineeducation.viewmodel.OfflineStudyDetailAcVM
import com.yc.jetpacklib.extension.showToast
import com.yc.jetpacklib.extension.ycIsNotEmpty
import com.yc.jetpacklib.extension.ycLoadImageNet
import com.yc.jetpacklib.net.doSuccess
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Creator: yc
 * Date: 2022/4/1 15:10
 * UseDes:线下学习列表的活动详情
 */
@SuppressLint("SetTextI18n")
class OfflineStudyDetailAc : BaseActivity<OfflineStudyDetailAcBinding>(OfflineStudyDetailAcBinding::inflate) {
    companion object {
        private const val KEY_PRO_ID = "key_pro_id"
        private const val KEY_STUDY_LIVE_ID = "key_study_live_id"
        private const val KEY_IS_PRO_MONITOR = "key_is_pro_monitor"

        /**
         * @param proId String          活动所在项目id
         * @param studyLiveId String    活动id
         * @param isProMonitor Boolean  用户是否是该活动所在项目的班组长
         */
        @JvmStatic
        fun newInstance(context: Context, proId: String, studyLiveId: String, isProMonitor: Boolean) {
            context.startActivity(Intent(context, OfflineStudyDetailAc::class.java).apply {
                putExtra(KEY_PRO_ID, proId)
                putExtra(KEY_STUDY_LIVE_ID, studyLiveId)
                putExtra(KEY_IS_PRO_MONITOR, isProMonitor)
            })
        }
    }

    private lateinit var mProId: String
    private lateinit var mStudyLiveId: String
    private var mIsProMonitor: Boolean = false
    private val mViewModel by ycViewModels<OfflineStudyDetailAcVM>()
    private var mBDLocation: BDLocation? = null
    private var mJobCheckLocation: Job? = null
    private var mStudyState: Int = OfflineStudyLiveState.ERROR//学习活动状态
    override fun OfflineStudyDetailAcBinding.initView() {
        actionBar.setTitle("活动详情")
        intent.apply {
            mProId = getStringExtra(KEY_PRO_ID)!!
            mStudyLiveId = getStringExtra(KEY_STUDY_LIVE_ID)!!
            mIsProMonitor = getBooleanExtra(KEY_IS_PRO_MONITOR, false)
        }
        App.mInstant.mBaiduLocationVM.mBDLocation.observe {
            mBDLocation = it
        }
        btnSignIn.setOnClickListener {
            sign(OfflineStudyLiveState.SERVICE_KEY_SIGN_IN)
        }
        btnSignOut.setOnClickListener {
            sign(OfflineStudyLiveState.SERVICE_KEY_SIGN_OUT)
        }
        btnReplacement.setOnClickListener {
            OfflineStudySignBehalfActivity.newInstance(this@OfflineStudyDetailAc, mStudyLiveId, mStudyState)
        }
        mViewModel.mSignResult.observe {
            it.ycShowNetResult()
            it.doSuccess {
                refreshData()
            }
        }
        mViewModel.mStudyLiveDetail.observe {
            it.doSuccess {
                if (it.studyLiveImgUrl.ycIsNotEmpty()) {
                    ivStudy.visibility = View.VISIBLE
                    ivStudy.ycLoadImageNet(it.studyLiveImgUrl)
                } else {
                    ivStudy.visibility = View.GONE
                }

                tvStudyName.text = it.studyLiveName
                tvAddress.text = it.signAddress
                tvTime.text = "${it.studyLiveTimeStart}~${it.studyLiveTimeEnd}"
                tvContent.text = it.studyLiveContent
                tvSignState.text = it.signStateName
                tvOfflineStudyState.text = it.studyLiveStateName
                mStudyState = it.studyLiveState
                if (it.studyLiveState == OfflineStudyLiveState.STUDY_LIVE_IN_PROGRESS || it.studyLiveState == OfflineStudyLiveState.STUDY_LIVE_FINISH_1_HOUR) {
                    //只有是班组长且活动状态是进行中/结束1小时内，可以签退，但不可以签到
                    btnReplacement.isVisible = mIsProMonitor
                    when (it.signState) {
                        OfflineStudyLiveState.SIGN_IN_FALSE -> {
                            if (it.studyLiveState == OfflineStudyLiveState.STUDY_LIVE_IN_PROGRESS) {
                                btnSignIn.visibility = View.VISIBLE
                            } else {
                                btnSignIn.visibility = View.GONE
                            }
                            btnSignOut.visibility = View.GONE
                        }
                        OfflineStudyLiveState.SIGN_IN_TRUE -> {
                            btnSignIn.visibility = View.GONE
                            btnSignOut.visibility = View.VISIBLE
                        }
                        OfflineStudyLiveState.SIGN_OUT_FALSE -> {
                            btnSignIn.visibility = View.GONE
                            btnSignOut.visibility = View.VISIBLE
                        }
                        OfflineStudyLiveState.SIGN_OUT_TRUE -> {
                            btnSignIn.visibility = View.GONE
                            btnSignOut.visibility = View.VISIBLE
                        }
                        else -> {
                            btnSignIn.visibility = View.GONE
                            btnSignOut.visibility = View.GONE
                            btnReplacement.visibility = View.GONE
                        }
                    }
                } else {
                    btnSignIn.visibility = View.GONE
                    btnSignOut.visibility = View.GONE
                    btnReplacement.visibility = View.GONE
                }
            }.ycShowFinishErrorDialog()
        }
        refreshData()
        App.mInstant.mBaiduLocationVM.start()
    }

    private fun refreshData() {
        mViewModel.getOfflineStudyLiveDetail(mProId, mStudyLiveId)
    }

    /**
     * 签到/签退
     * @param signType String
     */
    private fun sign(signType: String) {
        if (BaiduLocationUtil.checkOpenLocation().not()) {
            showToast("定位功能未开启！")
            BaiduLocationUtil.openGPS()
        } else {
            showLoading()
            mJobCheckLocation?.cancel()
            mJobCheckLocation = this.lifecycleScope.launch {
                var i = 1
                //防止无法获取经纬度问题
                while (BaiduLocationUtil.checkResult(mBDLocation)) {
                    if (i++ > 3) {
                        break
                    }
                    delay(1000)
                }
                if (BaiduLocationUtil.checkResult(mBDLocation)) {
                    mViewModel.offlineStudyLiveSignInOrSignOut(
                        mStudyLiveId,
                        mBDLocation!!.addrStr,
                        mBDLocation!!.latitude.toString(),
                        mBDLocation!!.longitude.toString(),
                        signType
                    )
                } else {
                    hideLoading()
                    showToast("gps信号弱,请重试!")
                }
            }
        }
    }

    override fun onDestroy() {
        App.mInstant.mBaiduLocationVM.stop()
        mJobCheckLocation?.cancel()
        super.onDestroy()
    }
}